import os
import json

from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from django.conf import settings

class DelView(APIView):
    '''
    删除本地图片功能
    '''

    def get(self, request, *args, **kwargs):
        # image:{"key":"ffc80dd45d634a29406215334879a55e.png","cos_path":"http://127.0.0.1:8000/media/ffc80dd45d634a29406215334879a55e.png"}
        imagePath = request.query_params.get('image', '')
        imagePath = json.loads(imagePath)
        MEDIA_ROOT = settings.MEDIA_ROOT
        try:
            # 1f75e5dfcf258de22566433799ce67a1.jpg
            file_path = os.path.join(os.getcwd(), MEDIA_ROOT + imagePath['key'])
            file_path = file_path.replace('/', '\\')
            os.remove(file_path)
            return Response({"status": True, "message": "图片删除成功"})
        except Exception as e:
            return Response({"status": False, "message": "图片删除失败:" + str(e)})


# 传图功能
class UploadView(APIView):
    '''
    上传图片功能
    '''

    def post(self, request, *args, **kwargs):
        # 传入的文件路径列表
        imageList = request.FILES.get('image', '')
        print(imageList)
        # imageList = request.FILES['image']
        # 文件类型，可以判断如果不是图片格式则不上传
        file_type = os.path.splitext(imageList.name)[1]
        if not imageList:
            print("上传文件不能为空")
            return JsonResponse({"status": False, "message": "上传文件不能为空"})
        file_format = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp', '.tif', '.tiff']
        if file_type.lower() not in file_format:
            print("上传文件类型非图片格式")
            return JsonResponse({"status": False, "message": "上传文件类型非图片格式"})
        #  获得一个唯一名字：uuid +hash
        new_name = self.get_random_str()
        # 组合成文件新名字
        new_file_name = new_name + file_type
        MEDIA_ROOT = settings.MEDIA_ROOT
        if not os.path.exists(MEDIA_ROOT):
            os.makedirs(MEDIA_ROOT)
        # 文件路径
        file_path = os.path.join(MEDIA_ROOT, new_file_name)
        # 将网络地址返回给小程序
        return_img = "http://127.0.0.1:8000/media/" + str(new_file_name)
        # 开始写入本地磁盘
        try:
            f = open(file_path, 'wb')
            # 多次写入
            for i in imageList.chunks():
                f.write(i)
            f.close()
            print("上传图片成功")
            # 不能用Response，result.data.status获取不到，result.data是string类型，不是object
            # return Response({"status": True, "message": "上传图片成功","data": file_path})
            # 如果返回的是JsonResponse，小程序要进行解析console.log(JSON.parse(res.data))
            return JsonResponse({"status": True, "message": "上传图片成功",
                                 "cos_path": return_img, "key": new_file_name})
        except Exception as e:
            print("上传图片失败：", e)
            return JsonResponse({"status": False, "message": "上传图片失败:" + str(e)})

    # 获取UUID
    def get_random_str(self):
        import hashlib
        import uuid
        """获取UUID"""
        uuid_val = uuid.uuid4()  # UUID('c1127b61-0714-4eab-8fb0-0138b6a84b4c')
        uuid_str = str(uuid_val).encode('utf-8')  # b'c1127b61-0714-4eab-8fb0-0138b6a84b4c'
        md5 = hashlib.md5()  # <md5 _hashlib.HASH object @ 0x00000253D50DCDB0>
        md5.update(uuid_str)
        return md5.hexdigest()  # 'fb8dfbe57e508bc4ade13f1ac4e7212b'
